import React from 'react';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {PAGINATION_OPTIONS, TABLE, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, DATE_FORMAT, FIXED_COLUMN_WIDTH} from '../constants';
import {injectIntl} from './intl';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {paymentType, partShipmentStatus, transportType, partOrderPriceTerms} from '../Enum';
import DropdownMenu from 'Shared/components/DropdownMenu';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {abandonData} from './api';
export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }

    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };
    onClickAbandonBtn = id => {
        this.setState({loading: true});
        const record = this.props.list.find(d => d.id === id);
        abandonData(id, {rowVersion: record.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.refreshListData();
            });
    }
    render() {
        const colums = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.dealerCode',
                    defaultMessage: '总代编号'
                }),
                dataIndex: 'dealerCode'
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.partContractInvoiceCode',
                    defaultMessage: '发票编号'
                }),
                dataIndex: 'partContractInvoiceCode',
                width: '100px',
                sorter: true,
                sortOrder: this.props.sortedColumnKey === 'partContractInvoiceCode' && this.props.sortedOrder,
                render: (text, record) => <Link to={routes.detail.format(record.id)} >{text}</Link>
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.invoicedDate',
                    defaultMessage: '开票日期'
                }),
                dataIndex: 'invoicedDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.shipmentType',
                    defaultMessage: '运输方式'
                }),
                dataIndex: 'shipmentType',
                render: text => conventEnumValueToString(transportType, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.paymentType',
                    defaultMessage: '付款方式'
                }),
                dataIndex: 'paymentType',
                render: text => conventEnumValueToString(paymentType, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.priceTerms',
                    defaultMessage: '价格条款'
                }),
                dataIndex: 'priceTerms',
                render: text => conventEnumValueToString(partOrderPriceTerms, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.invoiceAmount',
                    defaultMessage: '发票金额'
                }),
                dataIndex: 'invoiceAmount',
                render: text => formatAmount(text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '发运状态'
                }),
                dataIndex: 'status',
                render: text => conventEnumValueToString(partShipmentStatus, text)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.code',
                    defaultMessage: '发运单号'
                }),
                dataIndex: 'code'
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.createTime',
                    defaultMessage: '创建日期'
                }),
                dataIndex: 'createTime',
                render: text => formatDateTime(text, DATE_FORMAT)
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.operation',
                    defaultMessage: '操作'
                }),
                dataIndex: 'id',
                key: 'id',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (text, r) => {
                    const menus = [{
                        id: PERMISSION.update,
                        children: <Link key="update" to={routes.update.format(r.id)}>{
                            this.props.intl.formatMessage({
                                id: 'tablePanel.update',
                                defaultMessage: '编辑'
                            })
                        }</Link>,
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update)),
                    }, {
                        id: PERMISSION.abandon,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="abandon"
                                placement="topLeft"
                                onConfirm={this.onClickAbandonBtn}
                                id={r.id}
                                onVisibleChange={ref.setMenuVisible}
                                title={this.props.intl.formatMessage({
                                    id: 'tablePanel.validate.abandon',
                                    defaultMessage: '是否确认作废？'
                                })}>
                                <a>{
                                    this.props.intl.formatMessage({
                                        id: 'tablePanel.abandon',
                                        defaultMessage: '作废'
                                    })
                                }</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon)),
                    }];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            }];
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Table
                    className="white-space-nowrap"
                    columns={colums}
                    dataSource={this.props.list}
                    onChange={this.onChangeSort}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading || this.state.loading}
                    locale={locale}
                    {...TABLE} />
            </div>
        );
    }
}

TablePanel.propTypes = {
    errorMessage: PropTypes.string.isRequired,
    list: PropTypes.array.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    refreshListData: PropTypes.func,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    list: getData(state),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
    refreshListData: () => dispatch(tableSearch())
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
